import {
  addUserChannelByIdAPI,
  delUserChannelByIdAPI,
  getChannelListAPI,
  getuserChannelListAPI,
} from '@/api/channel';
import { getLocalChannels, hasToekn, setLocalChannels } from '@/utils/storage';
import { AppDispatch } from '..';
import { ChannelType } from '../reducer/channel';

export const getChannelListAction = () => {
  return async (dispatch: AppDispatch) => {
    const res = await getChannelListAPI();
    dispatch({
      type: 'channel/saveAllList',
      payload: res.data.channels,
    });
  };
};

export const getUserChannelListAction = () => {
  return async (dispatch: AppDispatch) => {
    if (hasToekn()) {
      const res = await getuserChannelListAPI();
      dispatch({
        type: 'channel/saveUserList',
        payload: res.data.channels,
      });
      return;
    }

    const localList = getLocalChannels();

    if (localList.length) {
      dispatch({ type: 'channel/saveUserList', payload: localList });
      return;
    }

    const res = await getChannelListAPI();
    dispatch({ type: 'channel/saveUserList', payload: res.data.channels.slice(0, 10) });
    setLocalChannels(res.data.channels.slice(0, 10));
  };
};

export const delUserChannelByIdAction = (id: number) => {
  return async (dispatch: AppDispatch) => {
    await delUserChannelByIdAPI(id);
    dispatch({ type: 'channel/delUserChannelById', payload: id });
  };
};

export const addUserChannelByIdAction = (newChannel: ChannelType) => {
  return async (dispatch: AppDispatch) => {
    await addUserChannelByIdAPI([newChannel]);

    dispatch({
      type: 'channel/addUserChannel',
      payload: newChannel,
    });
  };
};

export const setChannelIdAction = (id: number) => {
  return {
    type: 'channel/setChannelId',
    payload: id,
  };
};
